package web.admin.shop.product.checkboxtree;


import domain.shop.Category;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CategoryTreeNode extends DefaultMutableTreeNode {

    private boolean loading = false;
    @SpringBean
    private transient ShopAdminService shopAdminService;

    public CategoryTreeNode(Long categoryId) {
        super(new CategoryModel(categoryId), true);
        InjectorHolder.getInjector().inject(this);
    }

    public CategoryTreeNode(Category category) {
        super(new CategoryModel(category), true);
        InjectorHolder.getInjector().inject(this);
    }

    public Category getCategory() {
        CategoryModel model = (CategoryModel) getUserObject();

        return model.getCategory();
    }

    public Long getCategoryId() {
        CategoryModel model = (CategoryModel) getUserObject();

        return model.getId();
    }

    @Override
    public boolean isLeaf() {
        return false;
    }

    public void loadChildren() {

        if (loading == false) {
            loading = true;
            try {

                List<Category> categories = new ArrayList<Category>();

                try {
                    categories = shopAdminService.findCategoryChildsByParentId(getCategoryId());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                removeAllChildren();

                Collections.sort(categories, new CategoryComparator());

                for (Category category : categories) {
                    add(new CategoryTreeNode(category));
                }
            } finally {
                loading = false;
            }
        }

    }
}
